//
//  PEFirmwareUpgradeController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/8/3.
//

#import "RHFirmwareListVC.h"
#import "RHFirmwareUpgradeCell.h"
#import "RHAboutOneUpgradeController.h"
#import "RHNavigationController.h"


@interface RHFirmwareListVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *footView;

@property (nonatomic ,strong) NSArray *upgradeArr;

@property (nonatomic ,strong) NSMutableArray *selectFirmwares;

@property (nonatomic ,strong) QMUILabel *firmwareLab;

@property (nonatomic, assign) NSInteger updateIndex;

@property (nonatomic, strong) QMUINavigationButton *rightBtn;

@property (nonatomic, strong) QMUIButton *selectAllBtn;

@property (nonatomic, assign) BOOL hasSelected;
@end

@implementation RHFirmwareListVC
-(NSMutableArray *)selectFirmwares
{
    if(!_selectFirmwares){
        _selectFirmwares = [NSMutableArray array];
    }
    return _selectFirmwares;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self.navigationItem setTitle:@"固件升级".rh_localized];
    [self getDeviceFirmwareUpgradeList];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)getDeviceFirmwareUpgradeList
{
    [QMUITips showLoadingInView:self.view];
    [RHFirmwareModel startGetWithCompletionAPIKey:H_endUserUpgradeList argument:@{@"deviceId":ValidNullData(self.deviceModel.deviceId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.hasSelected = NO;
            NSArray *firmwareArr = resultModel.data;
            NSMutableArray *mtbArr = [NSMutableArray array];
            [firmwareArr enumerateObjectsUsingBlock:^(RHFirmwareModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //可以升和异常的显示
                if (obj.normal == 1 || obj.normal == 2) {
                    [mtbArr addObject:obj];
                }
                
            }];
            self.upgradeArr = mtbArr.copy;
            [self.tableView reloadData];
            [self.tableView endHeaderRefresh];
        }
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
        }];
}

- (void)setupUI{
    if(!self.isFromBle){
        QMUINavigationButton *rightBtn = [[QMUINavigationButton alloc] initWithImage:UIImageMake(@"ugrade_selectAll")];
        self.rightBtn = rightBtn;
        rightBtn.adjustsImageTintColorAutomatically = NO;
        [rightBtn setImage:[UIImage imageNamed:@"ugrade_cancelAll"] forState:UIControlStateSelected];
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem qmui_itemWithButton:rightBtn target:self action:@selector(selectAllAction:)];
    }
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHFirmwareUpgradeCell class] forCellReuseIdentifier:@"RHFirmwareUpgradeCell"];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImage:[UIImage imageNamed:@"nodata_icon_1"] titleStr:@"没有数据".rh_localized detailStr:@""];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0,0, 0));
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        weakSelf.firmwareLab.text = @"";
        [weakSelf.selectFirmwares removeAllObjects];
        weakSelf.rightBtn.selected = YES;
        [weakSelf selectAllAction:weakSelf.rightBtn];
        [weakSelf getDeviceFirmwareUpgradeList];
    }];
    
    _footView = [[UIView alloc] init];
    _footView.layer.cornerRadius = 15;
    _footView.layer.shadowColor = [UIColor blackColor].CGColor;
    
    [_footView setBackgroundColor:kCOLOR_HEX(@"ffffff")];
    [self.view addSubview:_footView];
    
    QMUIButton *selectAllBtn = [[QMUIButton alloc]init];
    [selectAllBtn setImage:[UIImage imageNamed:@"ugrade_cancel"] forState:UIControlStateNormal];
    [selectAllBtn setImage:[UIImage imageNamed:@"ugrade_select"] forState:UIControlStateSelected];
    [_footView addSubview:selectAllBtn];
    self.selectAllBtn = selectAllBtn;
    
    QMUILabel *firmwareLab = [[QMUILabel alloc] init];
    firmwareLab.numberOfLines = 0;
    [firmwareLab setTextAlignment:NSTextAlignmentLeft];
    [firmwareLab setTextColor:kCOLOR_HEX(@"3F4443")];
    [firmwareLab setFont:[UIFont systemFontOfSize:13]];
    [firmwareLab setText:[NSString stringWithFormat:@"%@:%ld",@"已选".rh_localized,self.selectFirmwares.count]];
    [_footView addSubview:firmwareLab];
    self.firmwareLab = firmwareLab;
    
    
    QMUIButton *upgradeBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [upgradeBtn setBackgroundColor:CMainColorGreen];
    [upgradeBtn setTitle:@"升级".rh_localized forState:UIControlStateNormal];
    [upgradeBtn setCornerRadius:8];
    
    [upgradeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [upgradeBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [_footView addSubview:upgradeBtn];
    
    
    [_footView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.offset(60+kSafe_bottom);
        make.bottom.mas_offset(60+kSafe_bottom);
    }];
    
    [selectAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(30);
        make.left.mas_offset(25);
        make.centerY.equalTo(upgradeBtn);
    }];
    
    [firmwareLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectAllBtn.mas_right).offset(15);
        make.centerY.equalTo(selectAllBtn);
    }];
    
    [upgradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.right.mas_offset(-20);
        make.width.offset(kScaleW(90));
        make.height.offset(kScaleW(40));
    }];
    
    
    
    [[selectAllBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.selectAllBtn.selected = weakSelf.selectAllBtn.selected;
        [weakSelf selectAllAction:weakSelf.rightBtn];
    }];
    [[upgradeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.updateIndex = 0;
        [weakSelf upgradeFireware];
    }];
}

#pragma mark - Action Method
- (void)learnMoreAction:(RHFirmwareModel*)firmwareModel{
    RHAboutOneUpgradeController *vc = [[RHAboutOneUpgradeController alloc] init];
    vc.firmwareModel = firmwareModel;
    RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)selectAllAction:(QMUINavigationButton*)button
{
    if(self.upgradeArr.count == 0)return;
    button.selected = !button.selected;
    if(button.selected){
        [self.selectFirmwares removeAllObjects];
        for (RHFirmwareModel *firmwareModel in self.upgradeArr) {
            firmwareModel.isClicked = YES;
            //异常固件 和 当前固件(这个应该后台过滤掉) 不能添加
            if((firmwareModel.normal != 2) && (firmwareModel.normal != 0)){
                firmwareModel.isSelected = YES;
                [self.selectFirmwares addObject:firmwareModel];
            }
        }
        
    }else{
        for (RHFirmwareModel *firmwareModel in self.upgradeArr) {
            firmwareModel.isSelected = NO;
        }
        [self.selectFirmwares removeAllObjects];
    }
    
    [self.tableView reloadData];
    self.selectAllBtn.selected = button.selected;
    [self.firmwareLab setText:[NSString stringWithFormat:@"%@:%ld",@"已选".rh_localized,self.selectFirmwares.count]];
    self.hasSelected = YES;
    
    [_footView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(0);
    }];
    
}



-(void)upgradeFireware
{
    if(self.upgradeArr.count == 0)return;
    if(self.selectFirmwares.count == 0){
        [QMUITips showError:@"请选择一个固件".rh_localized];
        return;
    }
    
    NSMutableArray *paraArr = [NSMutableArray array];
    
    [self.selectFirmwares enumerateObjectsUsingBlock:^(RHFirmwareModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        [paraArr addObject:model.endpoint];
    }];
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCodes":paraArr
                         };
    

    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_deviceUgrade argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"升级成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.selectFirmwares removeAllObjects];
                self.firmwareLab.text = @"";
                self.rightBtn.selected = YES;
                [self selectAllAction:self.rightBtn];
                [self getDeviceFirmwareUpgradeList];
        
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {

    }];
}




#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.upgradeArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kBottomToolBar+44;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHFirmwareUpgradeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHFirmwareUpgradeCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.firmwareModel = self.upgradeArr[indexPath.row];
    kWeakSelf;
    cell.learnMoreBlock = ^{
        [weakSelf learnMoreAction:weakSelf.upgradeArr[indexPath.row]];
    };
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if(self.hasSelected == NO && !self.isFromBle)return;
    RHFirmwareModel *model = self.upgradeArr[indexPath.row];
    //最新版本
    if (model.normal == 0) {
        [QMUITips showInfo:@"已经是最新固件".rh_localized];
        return;
    }
    
    if(model.normal == 2){
        __block NSMutableString *title = [NSMutableString string];
        __block NSString *currentVersion = @"";
        [model.sn enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj[@"normal"] integerValue] == 2){
                
                if(obj[@"sn"]){
                    [title appendString:[NSString stringWithFormat:@"SN:%@   V:%@",obj[@"sn"],obj[@"currentVersion"]]];
                    [title appendString:@"\n"];
                }
                
                currentVersion = obj[@"currentVersion"];
            }
        }];
       
        QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:@"此固件异常".rh_localized message:[NSString stringWithFormat:@"%@",title] preferredStyle:QMUIAlertControllerStyleAlert];
        QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:sure];
        [alertVC showWithAnimated:YES];
        return;
    }
    
    model.isSelected = !model.isSelected;
    if(model.isSelected){
        if(![self.selectFirmwares containsObject:model]){
            [self.selectFirmwares addObject:model];
        }
    }else{
        if([self.selectFirmwares containsObject:model]){
            [self.selectFirmwares removeObject:model];
        }
    }
    [self.firmwareLab setText:[NSString stringWithFormat:@"%@:%ld",@"已选".rh_localized,self.selectFirmwares.count]];
    [self.tableView reloadData];
}

@end
